﻿using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

namespace Jinndev {

    /// <summary>
    /// UI层级处理器
    /// </summary>
    [System.Obsolete]
    public class UILayerHelper : MonoBehaviour {

        public bool fullscreen;
        public bool destroyed;
        public UnityAction onDestroy;

        private void Awake() {
            // 默认配置
            fullscreen = true;
            destroyed = false;

            // 获取UI层级上的配置属性，没有则使用默认配置
            UIBase ui = gameObject.GetComponent<UIBase>();
            if(ui != null) {
                System.Type type = ui.GetType();
                object[] objs = type.GetCustomAttributes(typeof(UILayerAttribute), true);
                if(objs.Length > 0) {
                    UILayerAttribute attr = objs[0] as UILayerAttribute;
                    fullscreen = attr.fullscreen;
                }
            }

            if (fullscreen) {
                for(int i = transform.GetSiblingIndex() - 1; i >= 0; i--) {
                    GameObject child = transform.parent.GetChild(i).gameObject;
                    UILayerHelper helper = child.GetComponent<UILayerHelper>();
                    if(helper != null) {
                        child.SetActive(false);
                        if (helper.fullscreen) {
                            break;
                        }
                    }
                }
            }
        }

        private void OnDestroy() {
            destroyed = true;

            if (fullscreen) {
                for (int i = transform.GetSiblingIndex() - 1; i >= 0; i--) {
                    GameObject child = transform.parent.GetChild(i).gameObject;
                    UILayerHelper helper = child.GetComponent<UILayerHelper>();
                    if (helper.destroyed) {
                        break;  // 防止退出游戏/销毁父节点时报错
                    }
                    child.SetActive(true);

                    if (helper.fullscreen) {
                        break;
                    }
                }
            }

            if(onDestroy != null) {
                onDestroy.Invoke();
            }
        }

    }

}
